package com.admin.service;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import com.admin.dao.PetDao;
import com.admin.dao.TypeDao;
import com.bean.Pet;
import com.bean.Type;
@Service("PetServiceImp")
public class PetServiceImp implements PetService {
    @Autowired
    private PetDao PetDao;
	public String AdminUpdatePet(Pet Pet, Model model) {
		// TODO Auto-generated method stub
		int i=PetDao.updatePet(Pet);
		if(i>0) {
			model.addAttribute("mess","操作成功");
			List<Map<String,Object>>list=PetDao.getPet();
			model.addAttribute("list",list);
			return "admin/Petshow";
		}else {
			return "admin/error";
		}
	}
  
	public String AdminInsertPet(Pet Pet, HttpServletRequest request, MultipartFile mypic) {
		// TODO Auto-generated method stub
		if(!mypic.isEmpty()) {
			String gpic=uploadOneFile(mypic,request);
			Pet.setImg(gpic);	
		}
		int i=PetDao.insertPet(Pet);
		if(i>0) {
			request.setAttribute("mess","操作成功");
			List<Map<String,Object>>list=PetDao.getPet();
			request.setAttribute("list",list);
			return "admin/Petshow";
		}else {
			return "admin/error";
		}
	}
    
  
	public String AdminSelectPetById(int fid, Model model) {
		// TODO Auto-generated method stub
		Pet Pet=PetDao.selectById(fid);
		model.addAttribute("Pet",Pet);
		return "admin/Petupdate";
	}
 
	
	
	public String AdminDeletePet(int Petid,Model model) {
		int result=PetDao.deletePet(Petid);
		if(result>0) {
			model.addAttribute("mess","操作成功");
			List<Map<String,Object>>list=PetDao.getPet();
			model.addAttribute("list",list);
			return "admin/Petshow";
		}else {
			return "admin/error";
		}
	}
	
	public String AdminSelectPet(Model model) {
		// TODO Auto-generated method stub
		List<Map<String,Object>>list=PetDao.getPet();
		model.addAttribute("list",list);
		return "admin/Petshow";
	}
	
	public String uploadOneFile(MultipartFile myfile,
			 HttpServletRequest request) {
		 String realpath=request.getServletContext().
				 getRealPath("images");
		 File pathfile=new File(realpath);
		 if(!pathfile.exists()) {
			 pathfile.mkdirs();
		 }
		 String filename=myfile.getOriginalFilename();
		 String suffixList = "jpg,gif,png,ico,bmp,jpeg";
		 String type=filename.substring
				 (filename.lastIndexOf(".")+1,filename.length());
		 if(suffixList.contains(type.toLowerCase())) {
			//******************************************//
			 File tagrgetFile=new File(realpath,filename);
			 try {
				myfile.transferTo(tagrgetFile);
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return filename ;
		 }else {
			return null ;
		 }
	  }
}
